package com.huixue.cn.ztej.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Handle file upload
 * @author mxf
 */
public final class FileUploadUtils {

	private FileUploadUtils() {
	}

	private static final Logger LOG = LoggerFactory.getLogger(FileUploadUtils.class);

	public static final String FOLDER = "ZTEJ-Wechat"; // 系统文件夹的名称

	/**
	 * 在系统上传目录中创建文件夹
	 * 
	 * @param dir
	 * @return
	 */
	public static File createDirectory(String dir) {
		if (dir == null || dir.trim().length() == 0)
			dir = "unknow";
		String base = getUploadRoot();
		String path = base + dir + File.separator;

		File f = new File(path);
		if (!f.exists()) {
			f.mkdirs();
			LOG.info("dir '" + dir + "' created");
		}
		return f;
	}

	/**
	 * 删除文件
	 * 
	 * @param path
	 *            文件
	 */
	public static void deleteFile(File file) {
		if (file != null) {
			try {
				if (file.exists()) {
					file.delete();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param path
	 *            相对于上传根目录的文件路径
	 */
	public static void deleteFile(String path) {
		if (path != null) {
			try {
				File file = new File(getUploadRoot(), path);
				if (file.exists()) {
					file.delete();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 保存文件并且返回相对于文件上传根目录的文件路径
	 * 
	 * @param in
	 * @param dirName
	 * @param fileName
	 * @return the path of file
	 */
	public static String saveFile(InputStream in, String dirName, String fileName) {
		if (dirName == null || dirName.trim().length() == 0)
			dirName = "unknow";
		String name = Strings.uuid() + extensionName(fileName);
		File outFile = new File(createDirectory(dirName), name);
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(outFile);
			byte buf[] = new byte[4096];
			int len = -1;
			while ((len = in.read(buf)) != -1) {
				fos.write(buf, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			;
			try {
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			;
		}
		return FOLDER + File.separator + dirName + File.separator + name;
	}

	/**
	 * 获取文件上传的根目录，文件上传根目录是配置在config.properties文件中的upload.dir中，
	 * 如果没配置或者值为空，则会返回系统目录中的上传目录
	 * 
	 * @return
	 */
	public static String getUploadRoot() {
		String base = Config.getString("upload.dir");
		if (Strings.isEmpty(base))
			base = SGA.SERVLET_CONTEXT.getRealPath(File.separator);
		if (!base.endsWith("/") && !base.endsWith("\\"))
			base = base + File.separator;
		return base + FOLDER + File.separator;
	}

	/**
	 * Returns the extension name of a file name,note that with prefix "."
	 * 
	 * @param fileName
	 * @return
	 */
	public static String extensionName(String fileName) {
		if (fileName != null && fileName.lastIndexOf('.') > 0)
			return fileName.substring(fileName.lastIndexOf('.'));
		return "";
	}

	public static String genFileName(String originalFileName) {
		return Strings.uuid() + extensionName(originalFileName);
	}
}
